(function ($) {
  $(function () {
    // 左侧导航栏激活样式
    if (location.href.split('/')[0] == 'http:') {
      var item = location.href.split('/')[3].split('.')[0];
      if (!($('[name = ' + item + ']').hasClass('active'))) {
        $('[name = ' + item + ']').addClass('active').siblings().removeClass('active');
      }
    }

    $(document)
      // 单击某行
      .on('click', '[data-gctable] .gcBody tr', function () {
        $(this).addClass('bg-active').siblings().removeClass('bg-active');
      })
      .on('click', '[data-type]', function (e) {
        e.stopPropagation();
        var $data = $(this).data();
        if ($data.type === 2) {
          if ($data.modal === 'bagCollectedDetail') {
            getData($(this));
            return;
          }
          getdetail($(this));
        }
      })
  })
})(window.jQuery);

// 设定日期区间查询,接收参数(起始input id, 结束input id)
function setDateRange(startId, endId, min) {
  startId = startId || 'apply_start_date';
  endId = endId || 'apply_end_date';
  var apply_start_date = {
    elem: '#' + startId,
    min: min || '',
    choose: function (datas) {
      apply_end_date.min = datas; //开始日选好后，重置结束日的最小日期
      apply_end_date.apply_start_date = datas; //将结束日的初始值设定为开始日
    }
  },
    apply_end_date = {
      elem: '#' + endId,
      choose: function (datas) {
        apply_start_date.max = datas; //结束日选好后，重置开始日的最大日期
      }
    };
  laydate(apply_start_date);
  laydate(apply_end_date);
}

//  查看图片
function imgMagnify(imgUrl) {
  layer.open({
    type: 1,
    title: false,
    closeBtn: 2,
    area: '80%',
    offset: '10%',
    move: '.imgDrag',
    skin: 'layui-layer-nobg', //没有背景色
    shadeClose: true,
    content: '<div style="text-align: center">' +
      '<img  class="imgDrag" style="max-width:100%" src="' + imgUrl + '">' +
      '</div>'
  });
}

// 查找api
function getQuery(name, url) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = url.split('?')[1].match(reg);
  if (r != null)
    return unescape(r[2]);
  return null;
}

//  parsley验证
function validated($target) {
  var validated = true;
  $('[data-parsley-trigger]', $target).each(function () {
    $(this).parsley().validate();
    validated = $(this).parsley().isValid();
    if (!validated) {
      $(this).focus()
    }
    return validated;
  });
  return validated;
}

/**
 * 根据图片地址字符串渲染li
 * @param {Element}   target    显示容器的jquery对象
 * @param {String}    imgList   拼接图片地址字符串
 * @param {String}    glue      图片地址字符串分隔符 默认 '|'
 *
 * */
function randerImage(target, imgList, $triggers, hiding, glue) {
  glue = glue || '|';
  hiding = hiding || '';
  if (!imgList) {
    return false;
  }
  if (typeof imgList !== 'string') {
    return layer.alert('地址只能是字符串!');
  }
  imgList = imgList.split(glue);

  for (var i = 0, html = ''; i < imgList.length; i++) {
    var src = imgList[i];
    var img = new Image();
    img.onload = (function (src) {
      return function () {
        var ratio = this.naturalWidth / this.naturalHeight;
        var isV = ratio < 1
        var style = isV ?
          `top: -${(1 / ratio - 1) * 50}%` :
          `left: -${(ratio - 1) * 50}%`;

        html = '<li class="gc_item"> ' +
          '<img style="' + style + '" class="gc_item_' + (isV ? 'vertical' : 'horizontal') + '" src="' + src + '"> ' +
          '<span class="gc_item_action"> ' +
          '<span class="gc_preview">预览</span> ' +
          '<span class="gc_delete" style="display:' + hiding + '">删除</span> ' +
          '</span> ' +
          '</li>';
        target.append(html);
      }
    })(src)
    img.src = src;
  }
  if ($triggers.data('num') == 'one' && $($triggers.data('input')).val()) {
    $('.gc_upload_btn').hide();
  }
}

/* 上传图片函数封装 */
function gc_upload_image(el, $triggers) {
  var target = $($(el).data('input')),
    show = $('.gc_file_list'),
    tip = "图片格式不支持，请选择png/gif/bmp/jpeg/jpg格式的图片！", // 设定提示信息
    // uploadUrl = 'uploadPicture.do'; // 上传地址
    uploadUrl = 'https://www.easy-mock.com/mock/5a71293714298b5123dda1bf/upload/uploadPic'; // 上传地址

  if (typeof (FileReader) === 'undefined') {
    layer.msg("抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！");
    return false;
  }

  for (var i = 0, f; i < el.files.length; i++) {
    f = el.files[i];
    if (!/\.jpg$|\.png$|\.gif$|\.bmp$|\.jpeg/i.test(f.name)) {
      layer.msg(tip);
    } else {
      uploading(f);
    }
  }

  // for (var i = 0, f; i < el.files.length; i++) {
  //   f = el.files[i];
  //   if (!/\.jpg$|\.png$|\.gif$|\.bmp$|\.jpeg/i.test(f.name)) {
  //     layer.msg(tip);
  //   } else {
  //     var reader = new FileReader();
  //     reader.onload = function (e) {
  //       var result = this.result;
  //       var imgList = target.val();
  //       imgList += imgList == '' ? result : '|' + result;
  //       target.val(imgList);
  //       randerImage(show, result);
  //     }
  //     reader.readAsDataURL(f);
  //   }
  // }
  // 上传
  function uploading(f) {
    var form = new FormData();
    form.append("fileList", f);// 文件对象
    // XMLHttpRequest 对象
    var xhr = new XMLHttpRequest();
    xhr.open("post", uploadUrl, true);
    xhr.onload = function () {
      var responseText = xhr.responseText;
      // var responseText = JSON.parse(xhr.responseText).data;
      var imgList = target.val();
      imgList += imgList == '' ? responseText : '|' + responseText;
      target.val(imgList);
      randerImage(show, responseText, $triggers);
    };
    xhr.send(form);
  }
}

//  上传图片
$(document).on('click', '[data-upload=image]', function () {
  var $this = $(this),
    picHtml = '',
    hiding;
  picHtml += '<div class="gc_upload_image"> ' +
    '<ul class="gc_file_list"></ul> ';
  if ($this.val() == '上传图片' && $this.data('num') !== 'one') {
    picHtml += '<div class="gc_upload_btn"> ' +
      '<i class="gc_upload_icon">+</i> ' +
      '</div> ' +
      '<input multiple type="file" class="gc_upload_input" data-input="' + $this.data('input') + '"> '
  };
  if ($this.val() == '上传图片' && $this.data('num') == 'one') {
    var hidden = $($this.data('input')).val() ? 'none' : '';
    picHtml += '<div class="gc_upload_btn" style="display:' + hidden + '"> ' +
      '<i class="gc_upload_icon">+</i> ' +
      '</div> ' +
      '<input type="file" class="gc_upload_input" data-input="' + $this.data('input') + '"> '
  };
  picHtml += '</div>';
  /* 添加一个舞台 */
  $(document.body)
    .append(picHtml);
  var $box = $('.gc_upload_image');
  /* 首先根据input的值渲染图片*/
  $this.val() == '查看图片' && (hiding = 'none');
  randerImage($('.gc_file_list'), $($this.data('input')).val(), $this, hiding);
  $box
    .on('click', '.gc_upload_btn', function () {     //  上传按钮
      $(this).next().trigger('click');
    })
    .on('change', '.gc_upload_input', function () {  //  上传至服务器
      gc_upload_image(this, $this);
    })
    .on('click', '.gc_preview', function () {        //  预览
      imgMagnify($(this).parent().prev().attr('src'));
    })
    .on('click', '.gc_delete', function () {         //  删除
      var img = $(this).parent().prev(),
        url = img.attr('src'),
        imgInput = $($('.gc_upload_input').data('input'));
      img.parent().remove();
      if (imgInput.val() != '') {
        var arrImg = imgInput.val().split('|');
        for (var i = 0; i < arrImg.length; i++) {
          if (arrImg[i] == url) {
            arrImg.splice(i, 1);
            break;
          }
        }
        imgInput.val(arrImg.join('|'));
      }
      $this.data('num') == 'one' && $('.gc_upload_btn').show();
    });
  /* 展示舞台 */
  layer.open({
    type: 1,
    content: $box,
    title: $this.val(),
    area: '680px',
    shadeClose: true,
    end: function () { //  弹窗被销毁时触发的回调
      $('.gc_upload_image').remove();
      if ($($this.data('input')).val() != '') {
        if ($this.data('change')) {
          $this.addClass($this.data('change')).removeClass('btn-primary');
        }
        if ($this.data('changetext')) {
          $this.text($this.data('changetext'));
        }
      } else {
        if ($this.data('change')) {
          $this.removeClass($this.data('change')).addClass('btn-primary');
        }
        if ($this.data('changetext')) {
          $this.text('上传图片');
        }
      }
    }
  });
});

// 导出为excel
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {

  //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
  var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
  var CSV = '';
  //This condition will generate the Label/Header
  if (ShowLabel) {
    var row = "";

    //This loop will extract the label from 1st index of on array
    for (var index in arrData[0]) {
      //Now convert each value to string and comma-seprated
      row += index + ',';
    }
    // append Label row with line break
    CSV += row.slice(0, -1) + '\r\n';
  }

  //1st loop is to extract each row
  for (var i = 0; i < arrData.length; i++) {
    var row = "";
    //2nd loop will extract each column and convert it in string comma-seprated
    for (var index in arrData[i]) {
      row += '"' + arrData[i][index] + '",';
    }
    row.slice(0, row.length - 1);
    //add a line break after each row
    CSV += row + '\r\n';
  }

  if (CSV == '') {
    alert("Invalid data");
    return;
  }

  //this trick will generate a temp "a" tag
  var link = document.createElement("a");
  link.id = "lnkDwnldLnk";

  //this part will append the anchor tag and remove it after automatic click
  document.body.appendChild(link);

  var csv = CSV;
  blob = new Blob(['\ufeff' + csv], { type: 'text/csv' });
  // var csvUrl = 'data:text/csv;charset=utf-8,\ufeff' + encodeURI(csv);
  var csvUrl = window.URL.createObjectURL(blob);
  var filename = ReportTitle;
  $("#lnkDwnldLnk")
    .attr({
      'download': filename,
      'href': csvUrl
    });

  $('#lnkDwnldLnk')[0].click();
  document.body.removeChild(link);
}

/**
 * 获取弹窗详情并展示
 * @param {DOM} current
 */
function getdetail(current) {
  console.log(current.data());
  var checkUrl = '',
    cdata = current.data(),
    apiArr = cdata.api.split('?'),
    outerDiv = getQuery('outer', cdata.api), //最外层容器class
    outerTitle = current.text(),
    searchStr = getQuery('tp', cdata.api), //判断类型
    // read = searchStr == 'update' ? 'update/' : (searchStr == 'examine' ? 'examine/' : 'save/'),
    btn_content = searchStr == 'check' ? [] : ['确定'];//类型为修改、新增、审核
  // if (read) {
  //   checkUrl = '/' + apiArr[0] + '/' + read + cdata.id; //获取修改、新增弹窗
  // postUrl = '/' + apiArr[0] + '/' + read + cdata.id; //提交url
  postUrl = apiArr[0]; //提交url
  outerDiv == 'credit' && $("." + outerDiv).find('[name=userId]').val(cdata.id);
  outerDiv == 'djqAdd' && $("." + outerDiv).find('[name=userId]').val(cdata.id);
  //   $.get(checkUrl, {}, function (str) {
  console.log(searchStr);
  layer.open({
    type: 1,
    title: outerTitle,
    area: cdata.outwidth,
    offset: '50px',
    shadeClose: true,
    btn: btn_content,
    maxmin: true,
    content: cdata.modal ? MODALS[cdata.modal]({ ...cdata.json, readonly: searchStr === 'check' || searchStr === 'examine' }) : $("." + outerDiv),
    success: function () {
      // 认证信息&&商家概况
      if (outerDiv == 'identifydetail') {
        if (outerTitle == '审核') {
          $('.examine').show();
          // 选择审核不通过时，审核意见为必填
          $('.result').change(function () {
            $('[name=status]').val($(this).val() == '1' ? '2' : '3');
            if ($(this).val() == '2') {
              $(".opinionTxt").attr({
                'data-parsley-required': true,
                'data-parsley-trigger': 'change'
              })
            } else {
              $('.opinionTxt').val('').attr({
                'data-parsley-required': false,
              })
            }
          })
        } else if (outerTitle == '查看') {
          $('.examine').show();
          $('.result').hide();
          $('.resultText').show();
          // $('.result').attr('disabled', true);
          $('.opinionTxt').attr('disabled', true);
        } else {
          $('.examine').hide();
        }
      }
      $('.cashDispatch') && $('.cashDispatch').find('div:hidden').remove();
    },
    yes: function (i, stage) {
      var flag = validated($("." + outerDiv + " form"));
      if (flag) {
        // 新增代金券
        if (outerDiv == 'djqAdd' && parseInt($("#fullAmount").val()) < parseInt($("#reduceAmount").val())) {
          layer.msg('满额应大于等于减额', { time: 2000 });
          return;
        }
        var data = $("." + outerDiv + " form").serialize();
        var index = layer.load();
        $.post(postUrl, data, function (res) {
          if (res === '0') {
            layer.msg('提交成功', { time: 2000 }, function () {
              layer.close(i);
              location.reload();
            });
          } else if (res === 'NoJPush') {
            layer.msg('操作成功，但用户处于登出状态，无法产生推送消息!', { time: 2000 }, function () {
              layer.close(i);
              location.reload();
            });
          } else {
            layer.msg('提交失败', { time: 2000 });
          }
        })
          .complete(function () {
            layer.close(index);
          });
      }
    }
  });
  // });
  // }
}

/**
 * 获取弹窗详情并展示iframe :发布红包 红包领取详情 代金券领取详情 余额管理查看账单记录
 * @param {DOM} current
 */
function getData(current) {
  console.log(current.data());
  var checkUrl = '',
    cdata = current.data(),
    apiArr = cdata.api.split('?'),
    outerDiv = getQuery('outer', cdata.api), //最外层容器class
    outerTitle = current.text(),
    searchStr = getQuery('tp', cdata.api), //判断类型
    // symbol = $data.url.indexOf('?') == -1 ? '?' : '&',
    btn_content = searchStr == 'check' ? [] : ['确定'];//类型为修改、新增、审核

  checkUrl += apiArr[0] + '?';
  $.each(cdata.json, function (k, v) {
    checkUrl += k + '=' + v;
    k !== Object.keys(cdata.json).reverse()[0] && (checkUrl += '&');
  })
  var index = layer.open({
    type: 2,
    title: outerTitle,
    area: cdata.outwidth,
    offset: '50px',
    shadeClose: true,
    btn: btn_content,
    maxmin: true,
    content: checkUrl,
    success: function () {
      layer.iframeAuto(index);
    },
    yes: function () {
    }
  });
}